---
sidebar_position: 4
title: Sockets emitter
sidebar_label: useEmitter
---

# useEmitter

[Read the API Reference »](/docs/api/react/Hooks/useEmitter)

The `useEmitter` hook is your main tool for **sending events** to a server in React components. It integrates seamlessly
with Hyper Fetch's core systems, particularly the [`Emitter`](/docs/sockets/emitter), to deliver a robust, reactive, and
efficient event-emitting experience.

:::tip Purpose

1.  **Declarative event emitting**: Provide an `Emitter` and let the hook manage the process.
2.  **Automatic connection management**: Handles `connected` state for you.
3.  **Lifecycle callbacks**: Easily run side effects on events, errors, or reconnections.
4.  **Deep core integration**: Uses a central event dispatcher to send events.

:::

> If you intend to `listen` to events from the server, we recommend choosing the
> [`useListener`](/docs/react/sockets/use-listener) hook.

---

## Quick Start

To use `useEmitter`, provide a prepared [`Emitter`](/docs/sockets/emitter) instance. The hook returns an `emit` function
to send events and the current state of the socket connection.

First, let's define an emitter.

```tsx
// src/api/chat.ts
import { socketInstance } from "./socket";

export const emitMessage = socketInstance.createEmitter<ChatMessageType, AcknowledgementResponseType>()({
  endpoint: "chat-message", // endpoint of the event
});
```

Now, let's use it in a component.

```tsx
// src/components/MessageComponent.tsx
import { useEmitter } from "@hyper-fetch/react";
import { emitMessage } from "./api/chat";

const MessageComponent: React.FC = () => {
  const { emit, connected } = useEmitter(emitMessage);

  const onSubmit = (values: { message: string }) => {
    // ResponseDataType is automatically inherited from Emitter class
    const acknowledge = (error: Error, data: ResponseDataType) => {
      if (error) {
        alert("No server response!");
      } else {
        alert("Message received on server.");
      }
    };

    emit({ data: values }, acknowledge);
  };

  return (
    <Form onSubmit={onSubmit}>
      {/* ... form fields ... */}
      <button type="submit" disabled={!connected}>
        Send
      </button>
    </Form>
  );
};
```

<LinkCard
  type="docs"
  title="Emitter"
  description="Learn more about creating and configuring emitters."
  to="/docs/sockets/emitter"
/>

---

## Event Handlers

To handle side effects such as notifications, logging, or triggering other actions, `useEmitter` provides a set of event
handler hooks. This keeps your component's rendering logic clean and separates side effects from state management.

1.  `onEmit`: Fires before we send event message.
2.  `onEmitError`: Fires when an error occurs during the emission.
3.  `onConnected`: Fires when the socket connection is successfully opened.
4.  `onDisconnected`: Fires when the socket connection is closed.
5.  `onConnecting`: Fires when the socket is connecting.
6.  `onReconnecting`: Fires when the socket is attempting to reconnect.
7.  `onReconnectingFailed`: Fires when the socket fails to reconnect.

```tsx
import { useEmitter } from "@hyper-fetch/react";
import { emitMessage } from "./api";

const MessageComponent: React.FC = () => {
  const { emit, onEmit, onEmitError, onConnected, onDisconnected, onConnecting, onReconnecting, onReconnectingFailed } =
    useEmitter(emitMessage);

  onEmit((emitter) => {
    // Event before we send event message
    console.log(emitter); // Emitter instance
  });

  onEmitError((error) => {
    console.log(error); // Error Event
  });

  onConnected(() => {
    toast({ type: "info", message: "Socket connection opened." });
  });

  onDisconnected(() => {
    toast({ type: "warning", message: "Socket connection closed." });
  });

  onConnecting(() => {
    toast({ type: "info", message: "Socket is connecting." });
  });

  onReconnecting(({ attempts }) => {
    toast({ type: "warning", message: `Reconnecting... (attempt ${attempts})` });
  });

  onReconnectingFailed(({ attempts }) => {
    toast({ type: "error", message: `Reconnecting failed after ${attempts} attempts.` });
  });

  // ...
};
```

---

## Sending Data

Data can be passed in several ways. One option is to use `setData` method on the [`Emitter`](/docs/sockets/emitter).

```tsx
const { emit } = useEmitter(emitMessage.setData({ message: "New message" }));
```

However, you may need to pass data dynamically, which requires using the `emit` function.

```tsx
const { emit } = useEmitter(emitMessage);

const handleSubmit = (message: string) => {
  // ResponseDataType is automatically inherited from Emitter class
  emit({ data: { message } }, (error: Error, data: ResponseDataType) => {
    if (error) {
      alert("No server response!");
    } else {
      alert("Message received on server.");
    }
  });
};
```

---

## Options

Customize the behavior of `useEmitter` by passing an options object as the second argument.

```tsx
const { ... } = useEmitter(emitter, options)
```

(@import react UseEmitterOptionsType type=returns)

<LinkCard
  type="api"
  title="UseEmitterOptionsType API Reference"
  description="Learn more about the useEmitter hook options."
  to="/docs/api/react/Types/UseEmitterOptionsType"
/>

---

## Returns

`useEmitter` returns an object containing the socket's state and helper methods.

```tsx
const values = useEmitter(emitter);
```

(@import react useEmitter type=returns)

<LinkCard
  type="api"
  title="useEmitter API Reference"
  description="Learn more about the values returned from the useEmitter hook."
  to="/docs/api/react/Hooks/useEmitter"
/>

---

## See More

<LinkCard
  type="docs"
  title="useListener"
  description="Learn more about the useListener hook for receiving socket events."
  to="/docs/react/sockets/use-listener"
/>

<LinkCard type="docs" title="Emitter" description="Learn more about the Emitter class." to="/docs/sockets/emitter" />

<LinkCard
  type="docs"
  title="Socket"
  description="Learn more about creating a socket instance."
  to="/docs/sockets/socket"
/>
